<script setup>
import { ref, onMounted, nextTick } from 'vue'
import http from '@/utils/http'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
const messages = ref([])
const newMessage = ref('')
const messageListRef = ref(null)
const inputRef = ref(null)
const userStore = useUserStore()

// 获取消息列表，并按时间排序（最新的在最后）
const fetchMessages = async () => {
  const res = await http.get('employee_messages/')
  // 根据 MessageID 升序排序
  messages.value = res.data.sort((a, b) => a.MessageID - b.MessageID);
  scrollToBottom();
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return
  await http.post('employee_messages/', {
    AuthorName: userStore.name || '匿名',
    Content: newMessage.value
  })
  newMessage.value = ''
  fetchMessages() // 重新获取并排序
  focusInput()
}

// 删除消息
const deleteMessage = async (id) => {
  try {
    await http.post('employee_messages/delete/', {
      message_id: id,
      author_name: userStore.name
    })
    messages.value = messages.value.filter(msg => msg.MessageID !== id)
    ElMessage.success('删除成功')
  } catch (err) {
    ElMessage.error(err.response?.data?.error || '删除失败')
  }
}

// 时间格式化
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

// 自动聚焦输入框
const focusInput = () => {
  nextTick(() => {
    inputRef.value?.focus()
  })
}

onMounted(() => {
  fetchMessages()
})
</script>

<template>
  <div class="chat-container">
    <h2>员工交流区</h2>

    <div class="message-list" ref="messageListRef">
      <div v-for="msg in messages" :key="msg.MessageID" class="message">
        <div class="message-header">
          <strong>{{ msg.AuthorName }}：</strong>
          <el-button
            v-if="msg.AuthorName === userStore.name"
            link size="small"
            @click="deleteMessage(msg.MessageID)"
          >删除</el-button>
        </div>
        <span>{{ msg.Content }}</span>
        <div class="time">{{ formatTime(msg.PostTime) }}</div>
      </div>
    </div>

    <div class="input-area">
      <el-input
        v-model="newMessage"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
        ref="inputRef"
      />
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  max-width: 720px;
  margin: 60px auto;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding-right: 8px;
}

.message {
  padding: 12px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.2s ease;
}
.message:hover {
  background-color: #f9f9f9;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: rgb(124, 218, 66);
}

.time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.input-area {
  display: flex;
  gap: 12px;
}
</style>